import React, { useState, useEffect } from 'react';
import { Table, Card, Button, Space, message, Select, Input, Typography, Row, Col, Statistic, Tag, Spin, DatePicker } from 'antd';
import { ReloadOutlined, SearchOutlined, SyncOutlined, InfoCircleOutlined, TrophyOutlined, CalendarOutlined } from '@ant-design/icons';
import api from '../services/api';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import MainLayout from '../components/Layout/MainLayout';
import ResizableTable from '../components/ResizableTable';

const { Option } = Select;
const { Title, Text } = Typography;
const { Search } = Input;

interface FundNavRankingItem {
  id: number;
  fund_code: string;
  fund_name: string;
  fund_short_name: string;
  nav_date: string;
  unit_nav: number;
  cumulative_nav: number;
  daily_growth_rate: number;
  weekly_return: number;
  monthly_return: number;
  quarterly_return: number;
  half_year_return: number;
  yearly_return: number;
  two_year_return: number;
  three_year_return: number;
  since_inception_return: number;
  inception_date: string;
  management_fee: string;
  update_date: string;
  create_date: string;
}

interface FundNavRankingStats {
  available_dates: string[];
  latest_update: string | null;
  target_date: string;
  total_count: number;
  avg_daily_growth_rate: number;
  avg_yearly_return: number;
  avg_unit_nav: number;
}

interface PaginationInfo {
  current_page: number;
  page_size: number;
  total_pages: number;
  total_records: number;
  has_next: boolean;
  has_previous: boolean;
}

const FundNavRanking: React.FC = () => {
  const [data, setData] = useState<FundNavRankingItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [stats, setStats] = useState<FundNavRankingStats | null>(null);
  const [pagination, setPagination] = useState<PaginationInfo | null>(null);
  // Symbol分类和Indicator类型下拉框已移除
  const [sortBy, setSortBy] = useState<string>('daily_growth_rate');
  const [order, setOrder] = useState<string>('desc');
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(50);
  const [selectedNavDate, setSelectedNavDate] = useState<dayjs.Dayjs | null>(null);
  const [searchText, setSearchText] = useState<string>('');

  // 渲染增长率的函数
  const renderGrowthRate = (value: number | null) => {
    if (value === null || value === undefined) return '-';
    const numValue = typeof value === 'string' ? parseFloat(value) : value;
    if (isNaN(numValue)) return '-';
    const color = numValue > 0 ? '#f50' : numValue < 0 ? '#87d068' : '#666';
    return <span style={{ color }}>{numValue.toFixed(2)}%</span>;
  };

  const columns: ColumnsType<FundNavRankingItem> = [
    {
      title: '基金代码',
      dataIndex: 'fund_code',
      key: 'fund_code',
      width: 100,
      fixed: 'left',
      sorter: true,
    },
    {
      title: '基金名称',
      dataIndex: 'fund_name',
      key: 'fund_name',
      width: 200,
      fixed: 'left',
      ellipsis: true,
    },
    {
      title: '净值日期',
      dataIndex: 'nav_date',
      key: 'nav_date',
      width: 100,
    },
    {
      title: '单位净值',
      dataIndex: 'unit_nav',
      key: 'unit_nav',
      width: 100,
      render: (value: number) => value ? value.toFixed(4) : '-',
    },
    {
      title: '日增长率(%)',
      dataIndex: 'daily_growth_rate',
      key: 'daily_growth_rate',
      width: 120,
      render: renderGrowthRate,
      sorter: true,
    },
    {
      title: '累计净值',
      dataIndex: 'cumulative_nav',
      key: 'cumulative_nav',
      width: 100,
      render: (value: number) => value ? value.toFixed(4) : '-',
    },
    {
      title: '近1周(%)',
      dataIndex: 'weekly_return',
      key: 'weekly_return',
      width: 100,
      render: renderGrowthRate,
      sorter: true,
    },
    {
      title: '近1月(%)',
      dataIndex: 'monthly_return',
      key: 'monthly_return',
      width: 100,
      render: renderGrowthRate,
      sorter: true,
    },
    {
      title: '近3月(%)',
      dataIndex: 'quarterly_return',
      key: 'quarterly_return',
      width: 100,
      render: renderGrowthRate,
      sorter: true,
    },
    {
      title: '近6月(%)',
      dataIndex: 'half_year_return',
      key: 'half_year_return',
      width: 100,
      render: renderGrowthRate,
      sorter: true,
    },
    {
      title: '近1年(%)',
      dataIndex: 'yearly_return',
      key: 'yearly_return',
      width: 100,
      render: renderGrowthRate,
      sorter: true,
    },
    {
      title: '近2年(%)',
      dataIndex: 'two_year_return',
      key: 'two_year_return',
      width: 100,
      render: renderGrowthRate,
      sorter: true,
    },
    {
      title: '近3年(%)',
      dataIndex: 'three_year_return',
      key: 'three_year_return',
      width: 100,
      render: renderGrowthRate,
      sorter: true,
    },
    {
      title: '成立来(%)',
      dataIndex: 'since_inception_return',
      key: 'since_inception_return',
      width: 100,
      render: renderGrowthRate,
      sorter: true,
    },
    {
      title: '基金简称',
      dataIndex: 'fund_short_name',
      key: 'fund_short_name',
      width: 150,
      ellipsis: true,
    },
    {
      title: '成立日期',
      dataIndex: 'inception_date',
      key: 'inception_date',
      width: 100,
    },
    {
      title: '手续费',
      dataIndex: 'management_fee',
      key: 'management_fee',
      width: 100,
    },
    {
      title: '更新时间',
      dataIndex: 'update_date',
      key: 'update_date',
      width: 150,
    },
  ];

  const fetchData = async () => {
    setLoading(true);
    try {
      const params: any = {
        page: currentPage,
        page_size: pageSize,
        sort_by: sortBy,
        order: order,
      };
      
      // Symbol分类和Indicator类型参数已移除
      
      if (selectedNavDate) {
        params.nav_date = selectedNavDate.format('YYYY-MM-DD');
      }
      
      if (searchText.trim()) {
        params.fund_name = searchText.trim();
      }
      
      const response = await api.get('/data/fund-nav-ranking-stats/', { params });
      
      if (response.data.status === 'success') {
        setData(response.data.data || []);
        setPagination(response.data.pagination);
        setStats(response.data.statistics);
      } else {
        message.error(response.data.message || '获取基金排行数据失败');
      }
    } catch (error: any) {
      console.error('获取基金排行数据失败:', error);
      message.error('获取基金排行数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSync = async () => {
    if (syncing) {
      message.warning('同步任务正在进行中，请勿重复点击');
      return;
    }
    
    setSyncing(true);
    try {
      const response = await api.post('/data/fund-nav-ranking-stats/sync/');
      if (response.data.status === 'success') {
        message.success('同步任务已启动');
        // 延迟刷新数据
        setTimeout(() => {
          fetchData();
          setSyncing(false);
        }, 5000); // 增加延迟时间确保同步完成
      } else {
        message.error(response.data.message || '同步失败');
        setSyncing(false);
      }
    } catch (error: any) {
      console.error('同步失败:', error);
      message.error('同步失败');
      setSyncing(false);
    }
  };

  const handleTableChange = (paginationInfo: any, filters: any, sorter: any) => {
    if (sorter.field) {
      setSortBy(sorter.field);
      setOrder(sorter.order === 'ascend' ? 'asc' : 'desc');
    }
    
    if (paginationInfo.current !== currentPage) {
      setCurrentPage(paginationInfo.current);
    }
    
    if (paginationInfo.pageSize !== pageSize) {
      setPageSize(paginationInfo.pageSize);
      setCurrentPage(1); // 重置到第一页
    }
  };

  const handleSearch = (value: string) => {
    setSearchText(value);
    setCurrentPage(1); // 搜索时重置到第一页
  };

  const handleClearSearch = () => {
    setSearchText('');
    setCurrentPage(1);
  };

  useEffect(() => {
    fetchData();
  }, [currentPage, pageSize, sortBy, order, selectedNavDate, searchText]);

  return (
    <MainLayout>
      <div>
        <div style={{ marginBottom: 24 }}>
          <Title level={2}>基金排行数据</Title>
          <Text type="secondary">查看基金净值排行和收益统计</Text>
        </div>
        
        {/* 统计信息卡片 */}
        {stats && (
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="基金总数"
                  value={stats.total_count}
                  prefix={<InfoCircleOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="平均日增长率"
                  value={stats.avg_daily_growth_rate || 0}
                  precision={2}
                  suffix="%"
                  valueStyle={{ color: (stats.avg_daily_growth_rate || 0) > 0 ? '#52c41a' : '#ff4d4f' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="平均年增长率"
                  value={stats.avg_yearly_return || 0}
                  precision={2}
                  suffix="%"
                  valueStyle={{ color: (stats.avg_yearly_return || 0) > 0 ? '#52c41a' : '#ff4d4f' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="平均单位净值"
                  value={stats.avg_unit_nav || 0}
                  precision={4}
                  valueStyle={{ color: '#722ed1' }}
                />
              </Card>
            </Col>
          </Row>
        )}
      
      {/* 筛选和操作区域 */}
      <Card style={{ marginBottom: 24 }}>
        <Row gutter={16} align="middle">
          <Col span={5}>
            <Text strong>净值日期:</Text>
            <DatePicker
              style={{ width: '100%', marginTop: 8 }}
              placeholder="选择净值日期"
              allowClear
              value={selectedNavDate}
              onChange={setSelectedNavDate}
              format="YYYY-MM-DD"
              suffixIcon={<CalendarOutlined />}
            />
          </Col>
          <Col span={5}>
            <Text strong>基金名称:</Text>
            <Search
              style={{ width: '100%', marginTop: 8 }}
              placeholder="输入基金名称进行模糊查询"
              allowClear
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              onSearch={handleSearch}
              enterButton={<SearchOutlined />}
            />
          </Col>
          {/* Symbol分类和Indicator类型下拉框已移除 */}
          <Col span={5}>
            <Text strong>排序字段:</Text>
            <Select
              style={{ width: '100%', marginTop: 8 }}
              value={sortBy}
              onChange={setSortBy}
            >
              <Option value="daily_growth_rate">日增长率</Option>
              <Option value="weekly_growth_rate">周增长率</Option>
              <Option value="monthly_growth_rate">月增长率</Option>
              <Option value="quarterly_growth_rate">季度增长率</Option>
              <Option value="yearly_growth_rate">年增长率</Option>
              <Option value="ytd_growth_rate">今年来增长率</Option>
              <Option value="unit_nav">单位净值</Option>
              <Option value="fee_rate">手续费</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Text strong>排序方向:</Text>
            <Select
              style={{ width: '100%', marginTop: 8 }}
              value={order}
              onChange={setOrder}
            >
              <Option value="desc">降序</Option>
              <Option value="asc">升序</Option>
            </Select>
          </Col>
          <Col span={5}>
            <Space style={{ marginTop: 24 }}>
              <Button
                type="primary"
                icon={<ReloadOutlined />}
                onClick={fetchData}
                loading={loading}
              >
                刷新数据
              </Button>
              <Button
                icon={<SyncOutlined spin={syncing} />}
                onClick={handleSync}
                loading={syncing}
                disabled={syncing}
              >
                {syncing ? '同步中...' : '同步数据'}
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>
      
      {/* 数据表格 */}
      <Card>
        <ResizableTable
          columns={columns}
          dataSource={data}
          loading={loading}
          rowKey="id"
          scroll={{ x: 2000 }}
          pagination={{
            current: pagination?.current_page || 1,
            pageSize: pagination?.page_size || 50,
            total: stats?.total_count || 0,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            pageSizeOptions: ['20', '50', '100', '200'],
          }}
          onChange={handleTableChange}
        />
      </Card>
      
      {stats?.latest_update && (
        <div style={{ marginTop: 16, textAlign: 'center' }}>
          <Text type="secondary">
            最后更新时间: {stats.latest_update}
          </Text>
        </div>
      )}
      </div>
    </MainLayout>
  );
};

export default FundNavRanking;